<template>
  <div class="shopping">
    <CartItem
      ref="shopping"
      v-for="(pro, index) in products"
      :key="index"
      :id="parseInt(pro.id)"
      :name="pro.name"
      :img="pro.img"
      :price="pro.price"
      :num="parseInt(pro.num)"
      @changeFatherNum="receiveFromChild"
    ></CartItem>
    <button @click="pay">支付</button>
  </div>
</template>

<script>
//3.在父代中自定义事件名（与子代一致）
import CartItem from "../components/CartItem.vue";
export default {
  name: "CartList",
  data: function() {
    return {
      products: []
    };
  },
  created: function() {
    let products = JSON.parse(localStorage.getItem("cart")); //字符串->json对象
    this.products = products;
    // console.log("cartlist创建了");
  },
  mounted: function() {
    //mounted:'安装好的'
    //ref有对应的属性获取
    //console.log(this.$refs.shopping);
    for (let key in this.$refs.shopping) {
      this.$refs.shopping[key].$on("fromChildren", this.fromChildren); //on可以开启一个监听事件
      window.public1 = this.public
   }
  },
  components: {
    CartItem: CartItem
  },
  methods: {
    //接收单个参数
    receiveFromChild: function(num) {
      //num:子代传递过去的参数
      console.log("接收到了子代修改数据", num);
    },
    pay: function() {
      //提交到后台的接口 --to do
      //假设后台接口已经响应成功了，假设购买数量皆是1
      console.log('支付成功');
      this.public.$emit('reduceNum',1,1);
    },
    fromChildren(num, id) {
      console.log("接受子组件的实例");
      let products = JSON.parse(localStorage.getItem("cart"));
      for (let key in products) {
        let currentProduct = products[key];
        if (id==currentProduct.id) {
          currentProduct.num = num;
        }
      }
      localStorage.setItem("cart",JSON.stringify(products));
    }
    //接收多个参数
    // receiveFromChild:function(num,...args) {  //num:子代传递过去的参数
    //   console.log('接收到了子代修改数据',num,args);
    //   console.log('接收到了子代修改数据',num,,num2,args);
    // }
  }
};
</script>

<style scoped>
button {
  width: 100px;
  height:50px;
}
button {
  margin-left:900px;
  font-size: 20px;
  font-weight: 800;
}
</style>